<?php defined('SYSPATH') OR die('No direct access allowed.');

class Profile_Controller extends Master_Member_Controller 
{

	public function index() {
		$view = new View('member/profile');
		$this->set_title('โปรไฟล์');

		$auth=new Auth;
		$user = $auth->get_user(); 
		
		$profiles = new Profiles_Model();

		$form = array (
					'txtEmail'    => '',
					'txtUsername'   => '',
					'txtPassword' => '',
					'cboPrefix' => '',
					'txtFirstname' => '',
					'txtLastname' => '',
					'txtBirthdate' => '',
					'rdoSex' => '',
					'cboQuestion' => '',
					'txtAnswer' => '',
					'rdoMemberType' => '',
					'txtPicture' => '',
					'txtUsername' => '',
				);
				
		$data = $profiles->load($user->id);
			
		foreach ($data as $row)
		{
			$form['txtEmail'] = $row['email'];
			$form['cboPrefix'] = $row['prefix_id'];
			$form['txtFirstname'] = $row['firstname'];
			$form['txtLastname'] = $row['lastname'];
			$form['txtBirthdate'] = $row['birthdate'];
			$form['rdoSex'] = $row['sex'];
			$form['cboQuestion'] = $row['question_id'];
			$form['txtAnswer'] = $row['answer'];
			$form['rdoMemberType'] = $row['member_type'];
			$form['txtPicture'] = $row['picture'];
			$form['txtUsername'] = $row['username'];
		}
		
		$view->form = $form;
		$view->status = '';
		$view->errors = array();
		$this->load_master($view, $user->id);		
		$this->template->content = $view;
		$this->template->render(TRUE);
	}
	
	public function load_master($view, $id) {
		$master = new Masters_Model();
		
		// Get prefix master data
		$view->master_prefixs = $master->browse(2);
		// Get question master data
		$view->master_questions = $master->browse(3);
		// Get sex master data
		$view->master_sexs = $master->browse(4);
		// Get member type master data
		$view->master_member_types = $master->browse(5);
		
		$genes = new Genes_Model();
		$view->genes = $genes->loads();

		$clubs = new Clubs_Model();
		$view->clubs = $clubs->loads();
		
		$profiles = new Profiles_Model();
		$view->profile_clubs = $profiles->load_clubs($id);
		$view->profile_genes = $profiles->load_genes($id);
		
	}
	
	public function save() {
    	$view = new View('member/profile');

		$this->set_title('โปรไฟล์');
		$auth=new Auth;
		$user = $auth->get_user(); 

		if($_POST) {
    		$post = new Validation($_POST);
			$post->pre_filter('trim', TRUE);
            $post->add_rules('cboPrefix','required');
			$post->add_rules('txtFirstname','required', 'length[2,100]');
            $post->add_rules('txtLastname','required', 'length[2,150]');
            $post->add_rules('txtBirthdate','valid::date');
            $post->add_rules('rdoSex','required');
		    $post->add_rules('txtEmail', 'required', 'valid::email');
		    $post->add_rules('cboQuestion','required');
		    $post->add_rules('txtAnswer','required', 'length[2,100]');
        	$post->post_filter('ucfirst', 'name');
			$form = $post->as_array();

			if (!$post->validate())
	        {
	        	$errors = $post->errors('profile_error');
	        	$view->errors = $errors;
	        	
	        	$view->status = '';
	        }
	        else {
				$profiles = new Profiles_Model;
                $view->errors= array();
                
                $profiles->file_validate('txtPicture');
        		$filename = $profiles->get_filename();
				
                $view->errors= array();

                if (!empty($filename)) {
		        	$form['txtPicture'] = str_replace(DOCROOT, '', $profiles->get_filename());
        		}
                
	        	$txtPicture = '';
        		if (isset($form['txtPicture'])) {
        			$txtPicture = $form['txtPicture'];
        		}
                
                $data = array (
                	'id' => $user->id,
					'email'    => $form['txtEmail'],
					'prefix_id' => $form['cboPrefix'],
					'firstname' => $form['txtFirstname'],
					'lastname' => $form['txtLastname'],
					'birthdate' => $form['txtBirthdate'],
					'sex' => $form['rdoSex'],
					'question_id' => $form['cboQuestion'],
					'answer' => $form['txtAnswer'],
                	'picture' => $txtPicture,
				);

	        	if ($profiles->update($data)) {
	        		$view->status = Kohana::lang('profile_error.save_result.profile_save_completed');
	        	}
	        	else {
	        		$view->status = Kohana::lang('profile_error.save_result.save_failed');
	        	}
	        }
	        $view->form = $form;

	        $this->load_master($view, $user->id);
	       	$this->template->content = $view;
			$this->template->render(TRUE);
    	}
    }
    
    public function add_club($id) {
    	if(request::is_ajax())
	    {
	    	$this->auto_render=false;
	    	$ajax = new ISS_Ajax();
	    	
	    	$profiles = new Profiles_Model;
	    	$auth=new Auth;
			$user = $auth->get_user(); 
	    	if ($profiles->add_club($user->id, $id)) {
				$selector = 'selectedClubs';
				$content = '
					<div id="selectedClubs">
						<table>
					';
					$profile_clubs = $profiles->load_clubs($user->id);				
					foreach ($profile_clubs as $profile_club):
						$content .= '
							<tr>
								<td>' . html::specialchars($profile_club['name']) . '</td>
								<td>
									<a class="actionDelClub" href="' . url::base() . '/index.php/member/profile/del_club/'. $profile_club['club_id'] . '" ><img alt="ลบ" src="'. url::base() .'/media/images/delete.png"/></a>
								</td>
							</tr>';
			    	endforeach;
			    $content .= '								
						</table>
					</div>				
				';
	    		$ajax->addViewUpdate($selector, $content);
	    	}
	    	else {
		    	$tag = "alert";
			    $script = "alert('". Kohana::lang('profile_error.save_result.default') ."')";
				$ajax->addExecJScript($tag, $script);
	    	}
	    	echo json_encode($ajax->getHtmlAjax());
	    }
	    else {
	    	url::redirect('member/profile');
	    }	    	
    }
    
    public function add_gene($id) {
    	if(request::is_ajax())
	    {
	    	$this->auto_render=false;
	    	$ajax = new ISS_Ajax();
	    	
	    	$profiles = new Profiles_Model;
	    	$auth=new Auth;
			$user = $auth->get_user(); 
	    	if ($profiles->add_gene($user->id, $id)) {
				$selector = 'selectedGenes';
				$content = '
					<div id="selectedGenes">
						<table>
					';
					$profile_genes = $profiles->load_genes($user->id);				
					foreach ($profile_genes as $profile_gene):
						$content .= '
							<tr>
								<td>' . html::specialchars($profile_gene['name']) . '</td>
								<td>
									<a class="actionDelGene" href="' . url::base() . '/index.php/member/profile/del_gene/'. $profile_gene['gene_id'] . '" ><img alt="ลบ" src="'. url::base() .'/media/images/delete.png"/></a>
								</td>
							</tr>';
			    	endforeach;
			    $content .= '								
						</table>
					</div>				
				';
	    		$ajax->addViewUpdate($selector, $content);
	    	}
	    	else {
		    	$tag = "alert";
			    $script = "alert('". Kohana::lang('profile_error.save_result.default') ."')";
				$ajax->addExecJScript($tag, $script);
	    	}
	    	echo json_encode($ajax->getHtmlAjax());
	    }
	    else {
	    	url::redirect('member/profile');
	    }	    	
    }
    
    public function del_club($id) {
    	if(request::is_ajax())
	    {
	    	$this->auto_render=false;
	    	$ajax = new ISS_Ajax();
	    	
	    	$profiles = new Profiles_Model;
	    	$auth=new Auth;
			$user = $auth->get_user(); 
	    	if ($profiles->del_club($user->id, $id)) {
				$selector = 'selectedClubs';
				$content = '
					<div id="selectedClubs">
						<table>
					';
					$profile_clubs = $profiles->load_clubs($user->id);				
					foreach ($profile_clubs as $profile_club):
						$content .= '
							<tr>
								<td>' . html::specialchars($profile_club['name']) . '</td>
								<td>
									<a class="actionDelClub" href="' . url::base() . '/index.php/member/profile/del_club/'. $profile_club['club_id'] . '" ><img alt="ลบ" src="'. url::base() .'/media/images/delete.png"/></a>
								</td>
							</tr>';
			    	endforeach;
			    $content .= '								
						</table>
					</div>				
				';
	    		$ajax->addViewUpdate($selector, $content);
	    	}
	    	else {
		    	$tag = "alert";
			    $script = "alert('". Kohana::lang('profile_error.save_result.default') ."')";
				$ajax->addExecJScript($tag, $script);
	    	}
	    	echo json_encode($ajax->getHtmlAjax());
	    }
	    else {
	    	url::redirect('member/profile');
	    }	    	
    }
    
	public function del_gene($id) {
    	if(request::is_ajax())
	    {
	    	$this->auto_render=false;
	    	$ajax = new ISS_Ajax();
	    	
	    	$profiles = new Profiles_Model;
	    	$auth=new Auth;
			$user = $auth->get_user(); 
	    	if ($profiles->del_gene($user->id, $id)) {
				$selector = 'selectedGenes';
				$content = '
					<div id="selectedGenes">
						<table>
					';
					$profile_genes = $profiles->load_genes($user->id);				
					foreach ($profile_genes as $profile_gene):
						$content .= '
							<tr>
								<td>' . html::specialchars($profile_gene['name']) . '</td>
								<td>
									<a class="actionDelGene" href="' . url::base() . '/index.php/member/profile/del_gene/'. $profile_gene['gene_id'] . '" ><img alt="ลบ" src="'. url::base() .'/media/images/delete.png"/></a>
								</td>
							</tr>';
			    	endforeach;
			    $content .= '								
						</table>
					</div>				
				';
	    		$ajax->addViewUpdate($selector, $content);
	    	}
	    	else {
		    	$tag = "alert";
			    $script = "alert('". Kohana::lang('profile_error.save_result.default') ."')";
				$ajax->addExecJScript($tag, $script);
	    	}
	    	echo json_encode($ajax->getHtmlAjax());
	    }
	    else {
	    	url::redirect('member/profile');
	    }	    	
    }
    

}
